package com.example.springboot.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.springboot.common.Result;
import com.example.springboot.entity.User;
import com.example.springboot.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    /**
     * 登录
     */
    @PostMapping("/login")
    public Result<?> login(@RequestBody User user){
        LambdaQueryWrapper<User> wrapper = Wrappers.<User>lambdaQuery().eq(User::getUsername, user.getUsername()).eq(User::getPassword, user.getPassword());
        User res = userService.select(wrapper);
        if(res == null){
            return Result.error("-1", "用户名或密码错误");
        }
        return Result.success(res);
    }

    /**
     * 注册
     */
    @PostMapping("/register")
    public Result<?> register(@RequestBody User user){
        LambdaQueryWrapper<User> wrapper = Wrappers.<User>lambdaQuery().eq(User::getUsername, user.getUsername());
        User res = userService.select(wrapper);
        if(res != null){
            return Result.error("-1", "用户名已存在");
        }else {
            userService.insert(user);
            return Result.success();
        }
    }

    /**
     * 新增
     */
    @PostMapping
    public Result<?> save(@RequestBody User user){
        if(user.getPassword() == null){
            user.setPassword("123456");
        }
        userService.insert(user);
        return Result.success();
    }

    /**
     * 删除
     */
    @DeleteMapping("/{id}")
    public Result<?> remove(@PathVariable Integer id){
        userService.delete(id);
        return Result.success();
    }

    /**
     * 更新
     */
    @PutMapping
    public Result<?> update(@RequestBody User user){
        userService.update(user);
        return Result.success();
    }

    /**
     * 查询
     * @param pageNum 页数
     * @param pageSize 每页多少条
     * @param search 查询关键字
     */
    @GetMapping
    public Result<?> findPage(@RequestParam(defaultValue = "1") Integer pageNum,
                              @RequestParam(defaultValue = "10") Integer pageSize,
                              @RequestParam(defaultValue = "") String search){
        Page<User> userPage = userService.select(pageNum, pageSize, search);
        return Result.success(userPage);
    }
}
